import React, { useEffect, useState } from "react"
import LotteryBall from '../../../components/LotteryBall'
import { getFourNumbers, getFourNumbersSum, getWinningResult } from '../../../data/sortFiveUtils'

const REPEAT_COLOR = 'orange'
const SUM_COLOR = 'yellow'

function getWeekday(dateString) {
  const date = new Date(dateString);

  // 定义星期的数组
  const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];

  // 获取星期几，JavaScript中周一是0，周二是1，以此类推
  const weekdayIndex = date.getDay();

  // 返回对应的"周几"
  return weekdays[weekdayIndex];
}

const LotteryItem4SortFive = (props) => {
  const { item } = props
  const { filter } = item

  const [lineColor, setLineColor] = useState('gray')
  const [sumIndexArray, setSumIndexArray] = useState([])
  const [repeatIndexArray, setRepeatIndexArray] = useState([])

  useEffect(() => {

    let isSetGray = false
    const winningResult = getWinningResult(item)

    // 四位和值控制
    if (winningResult.fourPlaceSumStatus) {
      if (!isSetGray) { // 没置灰，可以修改颜色
        setLineColor('green')
      }
    } else {
      isSetGray = true
      setLineColor('gray')
    }

    // 同位重复控制
    if (winningResult.sameRepeatStatus) {
      setRepeatIndexArray([])// 清空
      if (!isSetGray) { // 没置灰，可以修改颜色
        setLineColor('green')
      }
    } else {
      setRepeatIndexArray(filter.repeatIndexArray)// 满足定位重复条件的索引
      isSetGray = true
      setLineColor('gray')
    }

  }, [JSON.stringify(filter)])

  // 获取小球颜色
  const getBallColor = (index) => {

    if (sumIndexArray.includes(index)) {
      return SUM_COLOR
    }

    if (repeatIndexArray.includes(index)) {
      return REPEAT_COLOR
    }

    return lineColor
  }

  return (
    <div className='lottery-item'>
      <div>
        {/* <div className='peroid-num'>第{item.lotteryDrawNum}期</div> */}
        <div className='peroid-date'>{item.lotteryDrawTime}</div>
        <div className='peroid-week'>{getWeekday(item.lotteryDrawTime)}</div>
      </div>
      <div>
        <div className='ball-wrapper'>
          {getFourNumbers(item.lotteryDrawResult).map((ball, index) => <LotteryBall key={`ball_${index}`} color={getBallColor(index)}>{ball}</LotteryBall>)}
        </div>
      </div>
      <div className='sum' style={{ color: lineColor, fontWeight: 500 }}>{getFourNumbersSum(item.lotteryDrawResult)}</div>
    </div>
  )
}

export default LotteryItem4SortFive